#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
音频上传并ASR识别示例
演示如何使用 /upload_and_asr 接口
"""

import requests
import json
import os

def upload_and_asr_example():
    """
    音频上传并ASR识别示例
    """
    # 服务端点
    url = "http://localhost:18080/upload_and_asr"
    
    # 示例音频文件路径（请替换为您的实际音频文件路径）
    audio_file_path = "/Users/songyuliang/Desktop/北京语言大学 3.m4a"
    
    # 检查文件是否存在
    if not os.path.exists(audio_file_path):
        print(f" 音频文件不存在: {audio_file_path}")
        print("请修改 audio_file_path 变量为您的实际音频文件路径")
        return
    
    # 请求参数
    request_data = {
        "file_path": audio_file_path,
        "identifier": "test_audio_example",  # 可选：用于缓存标识
        "use_cache": True  # 可选：是否使用ASR缓存
    }
    
    print(" 开始音频上传并ASR识别...")
    print(f"音频文件: {audio_file_path}")
    print(f"文件大小: {os.path.getsize(audio_file_path) / 1024 / 1024:.2f} MB")
    
    try:
        # 发送请求
        response = requests.post(
            url, 
            json=request_data,
            headers={"Content-Type": "application/json"},
            timeout=300  # 5分钟超时，ASR识别可能需要较长时间
        )
        
        # 解析响应
        result = response.json()
        
        if result["code"] == 0:
            print(" 音频上传并ASR识别成功!")
            
            # 上传信息
            upload_info = result["data"]["upload_info"]
            print(f"\n📤 上传信息:")
            print(f"  原始文件: {upload_info['original_file']}")
            print(f"  文件名: {upload_info['file_name']}")
            print(f"  文件大小: {upload_info['file_size']} 字节")
            print(f"  TOS对象键: {upload_info['object_key']}")
            print(f"  CDN访问链接: {upload_info['cdn_url']}")
            
            # ASR识别结果
            asr_result = result["data"]["asr_result"]
            print(f"\n ASR识别结果:")
            print(f"  缓存标识: {asr_result['identifier']}")
            print(f"  语音段数量: {asr_result['total_segments']}")
            print(f"  词数量: {asr_result['total_words']}")
            
            # 完整文本
            print(f"\n 完整识别文本:")
            print(f"  {asr_result['full_text']}")
            
            # 详细语音段信息
            print(f"\n 详细语音段:")
            for i, segment in enumerate(asr_result['segments'][:5]):  # 只显示前5个段
                print(f"  {i+1}. [{segment['start']:.2f}s - {segment['end']:.2f}s] {segment['text']}")
            
            if len(asr_result['segments']) > 5:
                print(f"  ... 还有 {len(asr_result['segments']) - 5} 个语音段")
            
            # 词级时间戳示例
            print(f"\n🔤 词级时间戳示例 (前10个词):")
            for i, word in enumerate(asr_result['words'][:10]):
                print(f"  {i+1}. [{word['start_time']:.2f}s - {word['end_time']:.2f}s] {word['text']} (置信度: {word['confidence']:.3f})")
            
            if len(asr_result['words']) > 10:
                print(f"  ... 还有 {len(asr_result['words']) - 10} 个词")
                
        else:
            print(f" 请求失败: {result['message']}")
            if result.get('data'):
                print(f"详细信息: {json.dumps(result['data'], ensure_ascii=False, indent=2)}")
    
    except requests.exceptions.Timeout:
        print(" 请求超时，ASR识别可能需要较长时间，请稍后重试")
    except requests.exceptions.ConnectionError:
        print(" 连接失败，请确保服务正在运行 (python app.py)")
    except Exception as e:
        print(f" 请求异常: {e}")

def test_health_check():
    """
    测试服务健康状态
    """
    try:
        response = requests.get("http://localhost:18080/check", timeout=5)
        result = response.json()
        if result["code"] == 0:
            print(" 服务运行正常")
            return True
        else:
            print(" 服务状态异常")
            return False
    except:
        print(" 无法连接到服务，请确保服务正在运行")
        return False

if __name__ == "__main__":
    print(" 音频上传并ASR识别示例")
    print("=" * 50)
    
    # 首先检查服务状态
    if test_health_check():
        print()
        upload_and_asr_example()
    else:
        print("\n请先启动服务:")
        print("  conda activate ai-english")
        print("  cd /Users/songyuliang/Desktop/qiniuyun")
        print("  python app.py")
